package com.rtx.edi.platform.synctask.handler;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.rtx.edi.model.api.bo.ApiMappingInfoBo;
import com.rtx.edi.model.api.po.PlApiMappingStructure;
import com.rtx.edi.model.asyntask.po.PlTaskQueue;
import com.rtx.edi.model.log.po.PlApiRequestLog;
import com.rtx.edi.model.response.EdiResponse;
import com.rtx.edi.model.response.ResultCode;
import com.rtx.edi.platform.asyntask.mapper.PlTaskQueueMapper;
import com.rtx.edi.platform.baseinfo.service.PlApiService;

import cn.hutool.http.HttpRequest;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import cn.hutool.json.XML;

/**
 * 异步任务处理
 */
@Component
public class PlTaskHandler {

    @Autowired
    private PlTaskQueueMapper plTaskQueueMapper;

    @Autowired
    private PlApiService plApiService;

    public void handler(){
    	
        //获取异步任务
        LambdaQueryWrapper<PlTaskQueue> queryWrapper = Wrappers.lambdaQuery();
        queryWrapper.eq(PlTaskQueue::getExecuteStatus,"P");
        List<PlTaskQueue> taskList = plTaskQueueMapper.selectList(queryWrapper);
        for(PlTaskQueue t : taskList){
        	PlApiRequestLog log =new PlApiRequestLog();
            //获取场景映射信息
            ApiMappingInfoBo apiInfo = plApiService.getApiMappingInfo(t.getCompanyId(),t.getApiMappingId(),log);
            //todo 获取报文结构 任务对象暂时没有增加报文字段
            //获取报文结构
            List<PlApiMappingStructure> structureList = plApiService.getPlApiMappingStructure(t.getApiMappingId());
            String requestJson = plApiService.convertJson(structureList, "");
            //发送请求
            String result = HttpRequest
                    .post(apiInfo.getTargetUrl())
                    .body(requestJson)
                    .timeout(30000)
                    .execute()
                    .body();
            //处理结果
            EdiResponse ediResponse = JSON.parseObject(result, EdiResponse.class);
            LambdaUpdateWrapper<PlTaskQueue> updateWrapper = Wrappers.lambdaUpdate();
            updateWrapper
                    .eq(PlTaskQueue::getId,t.getId())
                    .set(PlTaskQueue::getExecuteMsg,ediResponse.getReturnMgr())
                    .set(PlTaskQueue::getExecuteCount,t.getExecuteCount() + 1)
                    .set(PlTaskQueue::getExecuteStatus, ResultCode.SUCCESS.getCode() == ediResponse.getReturnCode() ? "S" : "E");
            plTaskQueueMapper.update(null,updateWrapper);
        }
    }
    
    public JSONObject getJSONObject(String requestStr) {
    	if((requestStr.startsWith("{")&&requestStr.endsWith("}"))||(requestStr.startsWith("[")&&requestStr.endsWith("]"))) {
    		return JSONUtil.parseObj(requestStr);
    	}else {
    		return XML.toJSONObject(requestStr);
    	}
    }
    
    
    public static void main(String[] args) {
		String s = "<request><actionType>update</actionType><extendProps><year>2019年</year></extendProps><item><barCode>8E0031717W9.E</barCode><brandName>宾度</brandName><categoryName>男鞋</categoryName><color>蓝色</color><goodsCode>8E00317</goodsCode><itemCode>8E0031717W9.E</itemCode><itemName>小牛皮胚男鞋</itemName><itemType>ZC</itemType><originAddress>ABC</originAddress><retailPrice>3999</retailPrice><size>9.0E</size></item><ownerCode>SHSH0100</ownerCode><warehouseCode>SHSH0100</warehouseCode></request>";
		System.out.println(JSONUtil.parseFromXml(s).toString());
		System.out.println(XML.toJSONObject(s,true));;
	}
}
